package com.wyz.socket.core.base;

import com.wyz.socket.core.api.IoProvider;
import com.wyz.socket.core.api.Scheduler;

import java.io.IOException;

/**
 * 上下文
 */
public class Context {

    private static Context INSTANCE; // 单例模式

    public static Context get() {
        return INSTANCE;
    }

    public static StartedBoot setup() {
        return new StartedBoot();
    }

    public static void close() throws IOException {
        if (INSTANCE != null) {
            INSTANCE.callClose();
        }
    }
    private final IoProvider ioProvider;
    private final Scheduler scheduler;

    private Context(IoProvider ioProvider, Scheduler scheduler) {
        this.ioProvider = ioProvider;
        this.scheduler = scheduler;
    }

    public IoProvider getIoProvider() {
        return ioProvider;
    }
    public Scheduler getScheduler() {
        return scheduler;
    }

    private void callClose() throws IOException {
        ioProvider.close();
        scheduler.close();
    }

    public static class StartedBoot {
        private IoProvider ioProvider;
        private Scheduler scheduler;
        public StartedBoot setIoProvider(IoProvider ioProvider) {
            this.ioProvider = ioProvider;
            return this ;
        }
        public StartedBoot setScheduler(Scheduler scheduler) {
            this.scheduler = scheduler;
            return this ;
        }
        private StartedBoot() {
        }
        public Context start() {
            return INSTANCE = new Context(ioProvider , scheduler);
        }
    }
}
